package com.nageoffer.jobtrain.projects.mq.producer;

import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.StrUtil;
import com.nageoffer.jobtrain.common.rocketmq.base.BaseSendExtendDTO;
import com.nageoffer.jobtrain.common.rocketmq.base.MessageWrapper;
import com.nageoffer.jobtrain.common.rocketmq.producer.AbstractCommonSendProduceTemplate;
import com.nageoffer.jobtrain.projects.common.constant.RocketMQContent;
import com.nageoffer.jobtrain.projects.mq.event.ContestRemindDelayEvent;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.common.message.MessageConst;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Component;

/**
 * 提醒用户竞赛即将开始生产者
 */
@Slf4j
@Component
public class ContestRemindDelayProducer extends AbstractCommonSendProduceTemplate<ContestRemindDelayEvent> {
    public ContestRemindDelayProducer(@Autowired RocketMQTemplate rocketMQTemplate) {
        super(rocketMQTemplate);
    }

    @Override
    protected BaseSendExtendDTO buildBaseSendExtendParam(ContestRemindDelayEvent messageSendEvent) {
        return BaseSendExtendDTO.builder()
                .eventName("提醒用户竞赛即将开始")
                // 使用（竞赛ID + 预约类型 + 预约时间 + 用户手机号）作为幂等标识判断
                .keys(messageSendEvent.getContestId() + ":" + messageSendEvent.getType() + ":"
                        + messageSendEvent.getRemindTime() + ":" + messageSendEvent.getPhoneNumber())
                .topic(RocketMQContent.USER_CONTEST_REMIND_TOPIC_KEY)
                .sendTimeout(2000L)
                .delayTime(messageSendEvent.getDelayTime())
                .build();
    }

    @Override
    protected Message<?> buildMessage(ContestRemindDelayEvent messageSendEvent, BaseSendExtendDTO requestParam) {
        String keys = StrUtil.isEmpty(requestParam.getKeys()) ? UUID.randomUUID().toString() : requestParam.getKeys();
        return MessageBuilder
                .withPayload(new MessageWrapper(keys, messageSendEvent))
                .setHeader(MessageConst.PROPERTY_KEYS, keys)
                .setHeader(MessageConst.PROPERTY_TAGS, requestParam.getTag())
                .build();
    }
}